#include <iostream>
#include <string>
#include <cstdio>
#include <string.h>
#include <errno.h>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


int fun()
{
    std::cout << "hello world" << std::endl;

    return 100;
    //exit(100);
}

int main()
{
    pid_t id = fork();
    if(id < 0)
    {
        printf("errno: %d, errstring: %s\n", errno, strerror(errno));
        return errno;
    }
    if(id == 0)
    {
        int cnt = 5;
        while(cnt)
        {
            printf("子进程运行中，pid: %d\n",getpid());
            cnt--;
            sleep(1);
        }
        exit(123);
    }
    else
    {
        //pid_t rid = wait(nullptr);
        
        int status = 0;
        //pid_t rid = waitpid(-1, nullptr, 0); // 等价于wait

        pid_t rid = waitpid(id, &status, 0); // 等价于wait

        

        if(rid > 0)
        {
            if(WIFEXITED(status))
            {
                printf("wait sub process success, rid: %d, status code: %d\n",rid, WEXITSTATUS(status));
            }
            else
            {
                printf("child process quit error!\n");
            }
            //printf("wait sub process success, rid: %d\n",rid);

           // printf("wait sub process success, rid: %``d, status code: %d, exit sigal: %d\n",rid, (status >> 8)&0xFF, status&0x7F);
        }
        while(true)
        {
            printf("我是父进程:pid:  %d\n",getpid());
            sleep(1);
        }
    }
    return 0;



    //printf("进程正常退出\n");
    //sleep(2);
    //exit(5);
    //sleep(2);


    //fun();
    //std::cout << "进程正常退出" << std::endl;

    //printf("before: errno:%d, errstring: %s\n",errno, strerror(errno));
    //FILE* fp = fopen("./log.txt","r");
    //if(fp == nullptr)
    //{
    //    printf("after: errno:%d, errstring: %s\n",errno, strerror(errno));
    //    return errno; 
    //}
    //std::cout << "hello" << std::endl;
    //return 10;
}
